package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.Voice;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService//操作桃花传音的api实现类
public class PeachblossomApiImpl implements PeachblossomApi {

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override//发送桃花传音语音
    public void save(Voice voice) {
        mongoTemplate.save(voice);
    }

    @Override//随机查询一条消息
    public Voice findByRandomOne(Long userId) {
        //1.构建条件.is("0").and("userId")
        Criteria isPickup = Criteria.where("isPickup").is("0");
        Criteria criteria = Criteria.where("userId").ne(userId).andOperator(isPickup);
        //2.构建Query
        Query query = Query.query(criteria);
        //3.根据条件查询字段为没有被拾取的音频
        return mongoTemplate.findOne(query, Voice.class);
    }

    @Override//根据id修改捞取状态
    public void updateById(Voice voice) {
        //1.构建条件
        Criteria criteria = Criteria.where("id").is(voice.getId());
        //2.构建Query
        Query query = Query.query(criteria);
        //3.构建Update对象
        Update update = new Update();
        update.set("isPickup","1");
        mongoTemplate.updateFirst(query,update,Voice.class);
    }
}
